package com.ihrm.company.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.company.dao.DepartmentDao;
import com.ihrm.domain.company.Department;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;
import java.util.List;

/**
 * @auther chongxiongwei
 * @create 2020-04-15-23:49
 */
@Slf4j
@Service
public class DepartmentService extends BaseService<Department> {

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private IdWorker idWorker;
    /**
     * 创建部门
     */
    public void save(Department department){

        String id = idWorker.nextId()+"";
        department.setId(id);
        department.setCreateTime(new Date(System.currentTimeMillis()));
        departmentDao.save(department);
    }
    /**
     * 更新部门
     * 1.先根据ID查找，
     * 2.更改数据
     * 3. 更新数据
     */
    public void update(Department department){
        // 先查询
        Department temp = departmentDao.findById(department.getId()).get();
        // 再修改属性
        temp.setCode(department.getCode());
        temp.setIntroduce(department.getIntroduce());
        temp.setName(department.getName());
        temp.setParentId(department.getParentId());
        // 更新数据
        departmentDao.save(temp);

    }
    /**
     * 根据部门ID删除部门
     */
    public void delete(String id){
        departmentDao.deleteById(id);
    }
    /**
     * 根据部门id查找部门
     */
    public Department findById(String id){
        return departmentDao.findById(id).get();
    }
    /**
     * 查找所有部门
     */
    public List<Department> findAll(String companyId){
        /*Specification<Department> specification = new Specification<Department>() {
            *//**
             * 构造查询条件
             * @param root   包含所有的对象属性
             * @param criteriaQuery
             * @param cb    构造查询条件
             * @return
             *//*
            @Override
            public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                return cb.equal(root.get("companyId").as(String.class),companyId);
            }
        };*/

        log.info("*****companyid******"+companyId);
        return departmentDao.findAll(getSpec(companyId));
    }
}
